package cm.example.shoppingplatformspringboot.service;


import cm.example.shoppingplatformspringboot.entity.Goods;
import cm.example.shoppingplatformspringboot.mapper.GoodsMapper;
import cm.example.shoppingplatformspringboot.utils.ProductResult;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class GoodsService {
    private final Random random = new Random();
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    // 写入缓存
    private void cacheResult(String key, @NotNull ProductResult result) {
        if (result.getGoodsList().isEmpty() && result.getTotals() == 0) {
            // 空结果缓存短时间（防止穿透）：缓存1-3分钟随机
            int ttl = 1 + random.nextInt(3);
            redisTemplate.opsForValue().set(key, result, ttl, TimeUnit.MINUTES);
        } else {
            // 正常结果：缓存30-35分钟随机
            redisTemplate.opsForValue().set(key, result, 30 + random.nextInt(6), TimeUnit.MINUTES);
        }
    }

    //分页查询商品列表
    public ProductResult selectAll(int page, int size) {
        String key = "goodsList:page:" + page + ":size:" + size; // 缓存key

        // 1. 尝试从缓存获取
        ProductResult cachedResult = (ProductResult) redisTemplate.opsForValue().get(key);
        if (cachedResult != null) {
            return cachedResult;
        }

        // 2. 查询数据库
        List<Goods> goodsList = goodsMapper.selectAll(page, size);
        int totals = goodsMapper.countAll();
        ProductResult dbResult = new ProductResult(goodsList, totals);

        // 3. 写入缓存
        cacheResult(key, dbResult);
        return dbResult;
    }

    //根据商品分类分页查询商品列表
    public ProductResult getGoodsListByGenre(String value, int page, int size) {
        String key = "goodsByGenre:genre:" + value + ":page:" + page + ":size:" + size; // 缓存key

        // 1. 尝试从缓存获取
        ProductResult cachedResult = (ProductResult) redisTemplate.opsForValue().get(key);
        if (cachedResult != null) {
            return cachedResult;
        }

        // 2. 查询数据库
        List<Goods> goodsList = goodsMapper.getGoodsListByGenre(value, page, size);
        int totals = goodsMapper.countGoodsByGenre(value);
        ProductResult dbResult = new ProductResult(goodsList, totals);

        // 3. 写入缓存
        cacheResult(key, dbResult);
        return dbResult;
    }

    //根据商品名称搜索商品列表
    public ProductResult searchGoods(String input, int page, int size) {
        String key = "goodsByName:name:" + input + ":page:" + page + ":size:" + size; // 缓存key

        // 1. 尝试从缓存获取
        ProductResult cachedResult = (ProductResult) redisTemplate.opsForValue().get(key);
        if (cachedResult != null) {
            return cachedResult;
        }

        // 2. 查询数据库
        List<Goods> goodsList = goodsMapper.searchGoods(input, page, size);
        int totals = goodsMapper.countGoodsByName(input);
        ProductResult dbResult = new ProductResult(goodsList, totals);

        // 3. 写入缓存
        cacheResult(key, dbResult);
        return dbResult;
    }

    //根据商品id查询商品详情
    public Goods fetchProductData(Integer id) {
        String key = "productData:id:" + id; // 缓存key

        // 1. 尝试从缓存获取
        Goods cachedProductData = (Goods) redisTemplate.opsForValue().get(key);
        if (cachedProductData != null) {
            return cachedProductData;
        }

        // 2. 查询数据库
        Goods productData = goodsMapper.selectById(id);

        // 3. 写入缓存
        redisTemplate.opsForValue().set(key, productData, 30 + random.nextInt(6), TimeUnit.MINUTES);
        return productData;
    }

    //获取热销商品列表
    public List<Goods> hottestGoods() {
        return goodsMapper.hottestGoods();
    }

    // 检查库存
    public boolean checkStock(Integer goodsId, Integer quantity) {
        Goods goods = goodsMapper.selectById(goodsId);
        return goods != null && goods.getStock() >= quantity;
    }

    // 根据商品id扣减商品库存
    public void reduceStock(Integer goodsId, Integer quantity) {
        goodsMapper.updateStock(goodsId, -quantity);
    }

    // 获取所有商品分类
    public List<Map<String, Object>> getAllShopGenres() {
        return goodsMapper.getAllShopGenres();
    }

    // 根据商品名称模糊搜索商品(返回商品名称列表)
    public List<String> searchGoodsByName(String name) {
        return goodsMapper.searchGoodsByName(name);
    }
}
